
package com.koron.css2.serviceManage.utils;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
public class RedisUtils {
	
    private static final int expire = 30 * 60;
    
    private static RedisTemplate<String, String> redisTemplate;

	private static RedissonClient redisson;

	@Autowired
	public void setRedisson(RedissonClient redisson) {
		RedisUtils.redisson = redisson;
	}

	public static RedissonClient redisson(){
		return redisson;
	}

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
    	RedisUtils.redisTemplate = redisTemplate;
	}

    public static void expire(String key, int seconds) {
        if (seconds > 0) {
        	redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        }
    }

    public static void del(String key) {
    	redisTemplate.delete(key);
    }

    public static void expire(String key) {
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }
    
    /**
	 * 判断key是否存在
	 * 
	 * @param key
	 *            键
	 * @return true 存在 false不存在
	 */
	public static boolean hasKey(String key) {
		return redisTemplate.hasKey(key);
	}
    
    /**
	 * 根据key 获取过期时间
	 * 
	 * @param key
	 *            键 不能为null
	 * @return 时间(秒) 返回0代表为永久有效
	 */
	public static long getExpire(String key) {
		return redisTemplate.getExpire(key, TimeUnit.SECONDS);
	}

    public static String get(String key) {
        return redisTemplate.boundValueOps(key).get()==null ? null : redisTemplate.boundValueOps(key).get().toString();
    }

    public static String setEx(String key, int seconds, String value) {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
        return key;
    }
    
    public static String set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
        return key;
    }
    
    public static long setnx(String key, String value) {
    	if(hasKey(key)) {
    		return -1L;
    	} else {
    		setEx(key, expire, value);
    		return 1L;
    	}
    }
    
    /**
	 * 向一张hash表中放入数据,如果不存在将创建
	 * 
	 * @param key
	 *            键
	 * @param item
	 *            项
	 * @param value
	 *            值
	 * @return true 成功 false失败
	 */
	public static boolean hset(String key, String item, String value) {
		try {
			redisTemplate.opsForHash().put(key, item, value);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
